package org.seven.jrdp.commons.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.seven.jrdp.commons.constant.GlobalContants;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.util.WebUtils;

public abstract class ServletUtils {
	public static boolean isAjax(HttpServletRequest request) {
		if (Boolean.valueOf(request.getParameter(GlobalContants.AJAX))) {
			return true;
		}
		if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equals("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}

	public static void writeJson(HttpServletResponse response, Object object) {
		try {
			response.reset();
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().print(JsonUtils.getJson(object));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void writeTimeout(HttpServletResponse response, String url) {
		try {
			PrintWriter out = response.getWriter();
			out.print(url);
			response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Map<String, Object> getSearchParams(HttpServletRequest request) {
		return WebUtils.getParametersStartingWith(request, GlobalContants.SEARCH_PREFIX);
	}

	public static void download(File file, HttpServletRequest request, HttpServletResponse response) {
		download(file, file.getName(), request, response);
	}

	public static void download(File file, String fileName, HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + transcode(fileName, request));
			InputStream in = new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			IOUtils.copy(in, out);
			in.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String getBody(HttpServletRequest request) {
		try {
			StringWriter out = new StringWriter();
			IOUtils.copy(request.getReader(), out);
			return out.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static PrintWriter getWriter(HttpServletResponse response) {
		try {
			return response.getWriter();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static WebApplicationContext getWebApplicationContext() {
		return ContextLoader.getCurrentWebApplicationContext();
	}

	public static <T> T getBean(Class<T> requiredType) {
		return getWebApplicationContext().getBean(requiredType);
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return getWebApplicationContext().getBean(name, requiredType);
	}

	public static ServletContext getServletContext() {
		return getWebApplicationContext().getServletContext();
	}

	public static String getExcelPath(String fileName) {
		return getServletContext().getRealPath("/") + GlobalContants.EXCEL_PATH + fileName;
	}

	public static void download(Workbook workbook, String fileName, HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + transcode(fileName, request));
			OutputStream out = response.getOutputStream();
			workbook.write(out);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String transcode(String fileName, HttpServletRequest request) {
		try {
			String agent = request.getHeader("User-Agent").toLowerCase();
			if (agent.indexOf("firefox") > 0) {
				fileName = StringUtils.toISO(fileName);
			} else if (agent.indexOf("chrome") > 0) {
				fileName = StringUtils.toISO(fileName);
			} else {
				fileName = URLEncoder.encode(fileName, GlobalContants.ENCODING_UTF);
			}
			return fileName;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}